package com.yt.order.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yt.order.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.order.mapper.WorkOrderInfoMapper;
import com.yt.order.models.bo.WorkOrderInfoSaveBO;
import com.yt.order.models.dto.WorkOrderInfoDTO;
import com.yt.order.models.service.IWorkOrderInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

/**
 * 工单信息控制器
 *
 * @author yzz
 * @Date 2025-09-03 14:15:17
 */
@Service
@org.apache.dubbo.config.annotation.DubboService(interfaceClass = IWorkOrderInfoService.class)
public class WorkOrderInfoServiceImpl extends ServiceImpl<WorkOrderInfoMapper, WorkOrderInfoDTO> implements IWorkOrderInfoService{

    @Resource
    private YmlConfig ymlConfig;
    
    @org.apache.dubbo.config.annotation.DubboReference
    private com.yt.order.models.service.IAutoDispatchService autoDispatchService;

    @Override
    public boolean add(WorkOrderInfoSaveBO saveBO) {
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        
        // 设置创建时间和更新时间
        Date now = new Date();
        dto.setCreateTime(now);
        dto.setUpdateTime(now);
        
        boolean result = this.insert(dto);
        
        // 如果订单添加成功且状态为待分配(0)，则触发自动派单
        if (result && dto.getStatus() != null && dto.getStatus() == 0) {
            try {
                autoDispatchService.handleOrderCreated(id);
            } catch (Exception e) {
                // 记录异常但不中断主流程
                e.printStackTrace();
            }
        }
        
        return result;
    }
    
    @Override
    public boolean assignOrder(Long id, Long dispatcherId, Long employeeId) {
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        dto.setId(id);
        dto.setDispatcherId(dispatcherId);
        dto.setEmployeeId(employeeId);
        dto.setStatus(1); // 设置为处理中状态
        return this.updateById(dto);
    }

    @Override
    public List<WorkOrderInfoDTO> selectByCustomerId(Long customerId) {
        Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("customer_id", customerId);
        return this.selectList(wrapper);
    }
    
    @Override
    public int countCompletedOrdersByEmployeeId(Long employeeId) {
        Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("employee_id", employeeId);
        wrapper.eq("status", 2); // 假设状态2表示已完成
        return this.selectCount(wrapper);
    }
    
    @Override
    public int countUnfinishedOrdersByEmployeeId(Long employeeId) {
        Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("employee_id", employeeId);
        wrapper.in("status", Arrays.asList(0, 1)); // 状态0待分配或1处理中表示未完成
        return this.selectCount(wrapper);
    }
    
    @Override
    public Map<Long, Integer> countAllEmployeesUnfinishedOrders() {
        // 查询所有未完成的订单（状态为0或1）
        Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.in("status", Arrays.asList(0, 1));
        wrapper.isNotNull("employee_id");
        
        List<WorkOrderInfoDTO> orders = this.selectList(wrapper);
        
        // 按员工ID分组并统计未完成订单数
        return orders.stream()
                .collect(Collectors.groupingBy(
                        WorkOrderInfoDTO::getEmployeeId,
                        Collectors.collectingAndThen(Collectors.counting(), Math::toIntExact)
                ));
    }
}